package tree.leetcode_297_hard;

import java.util.LinkedList;
import java.util.Queue;

public class BFSSolution {
    /*
        序列化二叉树
     */
    public String serialize(TreeNode root) {
        StringBuilder str = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                str.append(cur.val).append(",");
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                str.append("null,");
            }
        }
        return str.toString();
    }

    /*
        反序列化
     */
    public TreeNode deserialize(String data) {
        String[] values = data.split(",");
        int index = 0;
        if (values[index].equals("null")) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(values[index++]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (!values[index].equals("null")) {
                cur.left = new TreeNode(Integer.parseInt(values[index++]));
                queue.offer(cur.left);
            } else {
                index++;
            }
            if (!values[index].equals("null")) {
                cur.right = new TreeNode(Integer.parseInt(values[index++]));
                queue.offer(cur.right);
            } else {
                index++;
            }
        }
        return root;
    }
}
